from django.contrib import admin
from django.db.models import Max

from . import models
# Register your models here.
class BluekingJobsAdmin(admin.ModelAdmin):
    list_display = ('name', 'purpose', 'user', 'deploy_time', 'dev_project', 'dev_filename')
    fieldsets = (
        (None, {
            'fields': ('name', 'purpose', 'user', 'deploy_time', 'description')
        }),
        ('DEV', {
            'fields': ('dev_project', 'dev_filename')
        })
    )

    list_filter = ('dev_project', 'deploy_time')

admin.site.register(models.BluekingJobs, BluekingJobsAdmin)


class TaskProgressInline(admin.StackedInline):
    model = models.TaskProgress
    extra = 1
    ordering = ('-id',)
    max_num = 5

class TaskListAdmin(admin.ModelAdmin):
    ordering = ('-uptime',)
    list_display = ('name', 'staff', 'working_hours', 'latest_progress')
    inlines = [TaskProgressInline]
    list_filter = ('staff', 'customer', 'task_typ')

    def get_queryset(self, request):
        """替换查询语句
        增加一列是被关联的记录中创建时间最大的用于排序
        只有更新了关联的作业进展表才会使该作业的排序靠前
        """
        # 替换掉默认的基于Model的查询语句, 增加一列聚合的最新时间, 排序时会用到
        qs = models.TaskList.objects.annotate(Max('taskprogress__ctime'))
        ordering = self.get_ordering(request)
        if ordering:
            qs = qs.order_by(*ordering)
        return qs

    @admin.display(description='最新进展', ordering='taskprogress__ctime__max')
    def latest_progress(self, obj):
        last_taskprogress = obj.taskprogress_set.last()
        if last_taskprogress:
            return '{:%y-%m-%d} {}'.format(last_taskprogress.ctime, last_taskprogress.progress)


admin.site.register(models.TaskList, TaskListAdmin)



